<template>
  <div class="login">
    <!-- 导航栏 -->
    <NavBar
      title="登录"
      :left-arrow="true"
      @click-left="onBack"
      class="login__navbar"
    />

    <!-- 登录表单 -->
    <div class="login__container">
      <!-- Logo -->
      <div class="login__logo">
        <img src="/logo.png" alt="苒兴教育" class="login__logo-img" />
        <h1 class="login__title">苒兴教育</h1>
        <p class="login__subtitle">专业的在线学习平台</p>
      </div>

      <!-- 登录方式切换 -->
      <van-tabs v-model:active="loginType" class="login__tabs">
        <van-tab title="密码登录" name="password">
          <van-form @submit="onSubmit" class="login__form">
            <!-- 手机号 -->
            <van-field
              v-model="form.phone"
              name="phone"
              label="手机号"
              placeholder="请输入手机号"
              :rules="phoneRules"
              left-icon="phone-o"
              maxlength="11"
              type="tel"
            />
            
            <!-- 密码 -->
            <van-field
              v-model="form.password"
              name="password"
              label="密码"
              placeholder="请输入密码"
              :rules="passwordRules"
              left-icon="lock"
              :type="showPassword ? 'text' : 'password'"
              :right-icon="showPassword ? 'eye-o' : 'closed-eye'"
              @click-right-icon="showPassword = !showPassword"
            />
            
            <!-- 记住密码 -->
            <div class="login__options">
              <van-checkbox v-model="rememberPassword">记住密码</van-checkbox>
              <span class="login__forgot" @click="onForgotPassword">忘记密码？</span>
            </div>
            
            <!-- 登录按钮 -->
            <van-button
              type="primary"
              size="large"
              :loading="loading"
              native-type="submit"
              class="login__submit"
            >
              登录
            </van-button>
          </van-form>
        </van-tab>
        
        <van-tab title="验证码登录" name="sms">
          <van-form @submit="onSmsSubmit" class="login__form">
            <!-- 手机号 -->
            <van-field
              v-model="smsForm.phone"
              name="phone"
              label="手机号"
              placeholder="请输入手机号"
              :rules="phoneRules"
              left-icon="phone-o"
              maxlength="11"
              type="tel"
            />
            
            <!-- 验证码 -->
            <van-field
              v-model="smsForm.code"
              name="code"
              label="验证码"
              placeholder="请输入验证码"
              :rules="codeRules"
              left-icon="shield-o"
              maxlength="6"
              type="number"
            >
              <template #button>
                <van-button
                  size="small"
                  type="primary"
                  :disabled="!canSendSms || smsCountdown > 0"
                  :loading="sendingSms"
                  @click="sendSmsCode"
                  class="login__sms-btn"
                >
                  {{ smsCountdown > 0 ? `${smsCountdown}s后重发` : '发送验证码' }}
                </van-button>
              </template>
            </van-field>
            
            <!-- 登录按钮 -->
            <van-button
              type="primary"
              size="large"
              :loading="loading"
              native-type="submit"
              class="login__submit"
            >
              登录
            </van-button>
          </van-form>
        </van-tab>
      </van-tabs>

      <!-- 第三方登录 -->
      <div class="login__social">
        <div class="login__social-title">其他登录方式</div>
        <div class="login__social-buttons">
          <div class="login__social-btn" @click="onWechatLogin">
            <van-icon name="wechat" color="#07c160" size="24" />
            <span>微信</span>
          </div>
          <div class="login__social-btn" @click="onQQLogin">
            <van-icon name="qq" color="#1296db" size="24" />
            <span>QQ</span>
          </div>
        </div>
      </div>

      <!-- 注册链接 -->
      <div class="login__register">
        <span>还没有账号？</span>
        <span class="login__register-link" @click="onRegister">立即注册</span>
      </div>

      <!-- 协议 -->
      <div class="login__agreement">
        <van-checkbox v-model="agreeTerms" icon-size="14px">
          我已阅读并同意
          <span class="login__agreement-link" @click="onUserAgreement">《用户协议》</span>
          和
          <span class="login__agreement-link" @click="onPrivacyPolicy">《隐私政策》</span>
        </van-checkbox>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'
import NavBar from '@/components/common/NavBar.vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 登录类型
const loginType = ref('password')

// 密码登录表单
const form = ref({
  phone: '',
  password: ''
})

// 短信登录表单
const smsForm = ref({
  phone: '',
  code: ''
})

// 表单状态
const loading = ref(false)
const showPassword = ref(false)
const rememberPassword = ref(false)
const agreeTerms = ref(false)

// 短信相关
const sendingSms = ref(false)
const smsCountdown = ref(0)
let smsTimer = null

// 表单验证规则
const phoneRules = [
  { required: true, message: '请输入手机号' },
  { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
]

const passwordRules = [
  { required: true, message: '请输入密码' },
  { min: 6, message: '密码至少6位' }
]

const codeRules = [
  { required: true, message: '请输入验证码' },
  { pattern: /^\d{6}$/, message: '请输入6位数字验证码' }
]

// 是否可以发送短信
const canSendSms = computed(() => {
  return /^1[3-9]\d{9}$/.test(smsForm.value.phone)
})

// 返回上一页
const onBack = () => {
  const redirect = route.query.redirect
  if (redirect) {
    router.push(redirect)
  } else {
    router.back()
  }
}

// 密码登录
const onSubmit = async () => {
  if (!agreeTerms.value) {
    showToast('请先同意用户协议和隐私政策')
    return
  }

  loading.value = true
  try {
    await userStore.login({
      phone: form.value.phone,
      password: form.value.password,
      remember: rememberPassword.value
    })
    
    showToast('登录成功')
    
    // 跳转到指定页面或首页
    const redirect = route.query.redirect || '/'
    router.replace(redirect)
  } catch (error) {
    showToast(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 短信登录
const onSmsSubmit = async () => {
  if (!agreeTerms.value) {
    showToast('请先同意用户协议和隐私政策')
    return
  }

  loading.value = true
  try {
    await userStore.smsLogin({
      phone: smsForm.value.phone,
      code: smsForm.value.code
    })
    
    showToast('登录成功')
    
    // 跳转到指定页面或首页
    const redirect = route.query.redirect || '/'
    router.replace(redirect)
  } catch (error) {
    showToast(error.message || '登录失败')
  } finally {
    loading.value = false
  }
}

// 发送短信验证码
const sendSmsCode = async () => {
  if (!canSendSms.value) {
    showToast('请输入正确的手机号')
    return
  }

  sendingSms.value = true
  try {
    // 这里调用发送短信的API
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    
    showToast('验证码已发送')
    
    // 开始倒计时
    smsCountdown.value = 60
    smsTimer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(smsTimer)
        smsTimer = null
      }
    }, 1000)
  } catch (error) {
    showToast(error.message || '发送失败')
  } finally {
    sendingSms.value = false
  }
}

// 忘记密码
const onForgotPassword = () => {
  router.push('/forgot-password')
}

// 注册
const onRegister = () => {
  router.push('/register')
}

// 微信登录
const onWechatLogin = () => {
  showToast('微信登录功能开发中')
}

// QQ登录
const onQQLogin = () => {
  showToast('QQ登录功能开发中')
}

// 用户协议
const onUserAgreement = () => {
  router.push('/user-agreement')
}

// 隐私政策
const onPrivacyPolicy = () => {
  router.push('/privacy-policy')
}

// 页面初始化
onMounted(() => {
  // 如果已经登录，直接跳转
  if (userStore.isLoggedIn) {
    const redirect = route.query.redirect || '/'
    router.replace(redirect)
  }
})

// 页面销毁
onUnmounted(() => {
  if (smsTimer) {
    clearInterval(smsTimer)
  }
})
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';
@import '@/styles/mixins.scss';

.login {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

  &__navbar {
    background: transparent;
    color: white;
    
    :deep(.navbar__title-text) {
      color: white;
    }
    
    :deep(.navbar__arrow) {
      color: white;
    }
  }

  &__container {
    padding: $spacing-xl $spacing-base;
    min-height: calc(100vh - $navbar-height);
  }

  &__logo {
    text-align: center;
    margin-bottom: $spacing-2xl;
  }

  &__logo-img {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    margin-bottom: $spacing-base;
  }

  &__title {
    font-size: $font-size-3xl;
    font-weight: $font-weight-bold;
    color: white;
    margin: 0 0 $spacing-xs 0;
  }

  &__subtitle {
    font-size: $font-size-base;
    color: rgba(255, 255, 255, 0.8);
    margin: 0;
  }

  &__tabs {
    background: white;
    border-radius: $border-radius-xl;
    overflow: hidden;
    margin-bottom: $spacing-xl;
    
    :deep(.van-tabs__nav) {
      background: white;
    }
    
    :deep(.van-tab) {
      color: $text-color-light;
    }
    
    :deep(.van-tab--active) {
      color: $primary-color;
    }
  }

  &__form {
    padding: $spacing-base;
  }

  &__options {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: $spacing-base 0;
    padding: 0 $spacing-base;
  }

  &__forgot {
    color: $primary-color;
    font-size: $font-size-sm;
    cursor: pointer;
  }

  &__submit {
    margin-top: $spacing-lg;
    border-radius: $border-radius-xl;
  }

  &__sms-btn {
    border-radius: $border-radius-base;
    font-size: $font-size-xs;
  }

  &__social {
    background: white;
    border-radius: $border-radius-xl;
    padding: $spacing-lg;
    margin-bottom: $spacing-lg;
  }

  &__social-title {
    text-align: center;
    color: $text-color-light;
    font-size: $font-size-sm;
    margin-bottom: $spacing-base;
    position: relative;
    
    &::before,
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      width: 60px;
      height: 1px;
      background: $border-color;
    }
    
    &::before {
      left: 20px;
    }
    
    &::after {
      right: 20px;
    }
  }

  &__social-buttons {
    display: flex;
    justify-content: center;
    gap: $spacing-xl;
  }

  &__social-btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: $spacing-xs;
    padding: $spacing-base;
    border-radius: $border-radius-base;
    cursor: pointer;
    transition: all $transition-duration-fast;
    
    span {
      font-size: $font-size-xs;
      color: $text-color-light;
    }
    
    &:active {
      background: $gray-100;
      transform: scale(0.95);
    }
  }

  &__register {
    text-align: center;
    color: white;
    font-size: $font-size-sm;
    margin-bottom: $spacing-lg;
  }

  &__register-link {
    color: #ffd700;
    cursor: pointer;
    text-decoration: underline;
  }

  &__agreement {
    text-align: center;
    
    :deep(.van-checkbox) {
      color: rgba(255, 255, 255, 0.8);
      font-size: $font-size-xs;
    }
  }

  &__agreement-link {
    color: #ffd700;
    cursor: pointer;
    text-decoration: underline;
  }
}

// 响应式适配
@include respond-below(480px) {
  .login {
    &__container {
      padding: $spacing-lg $spacing-base;
    }
    
    &__logo {
      margin-bottom: $spacing-lg;
    }
    
    &__title {
      font-size: $font-size-2xl;
    }
  }
}
</style>